package cn.wen233.srpc.core.serialize;

import cn.wen233.srpc.basic.serialize.Serializer;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ser.SerializerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * Json 序列化器
 *
 * @author wenei
 * @date 2021-10-27 15:44
 */
public class JsonSerializer implements Serializer {

    private static final Logger LOGGER = LoggerFactory.getLogger(JsonSerializer.class);

    private static final ObjectMapper objectMapper = new ObjectMapper();

    static {
//        todo 反序列化时Object被解析成了Map
        //        objectMapper.getDeserializationConfig().findTypeDeserializer()
    }

    @Override
    public byte[] serialize(Object obj) {
        byte[] bytes = new byte[0];
        try {
            bytes = objectMapper.writeValueAsBytes(obj);
        } catch (JsonProcessingException e) {
            LOGGER.warn("Json序列化时出现问题", e);
        }
        return bytes;
    }

    @Override
    public <T> T deserialize(byte[] bytes, Class<T> clazz) {
        T obj = null;
        try {
             obj = objectMapper.readValue(bytes, clazz);
        } catch (IOException e) {
            LOGGER.warn("Json反序列化时出现问题", e);
        }
        return obj;
    }
}
